#coding=utf-8
'''
2.4. Matching and Searching for Text Patterns:
 use regular expressions and the  re module
 import re

 The essential functionality is first compiling a pattern using
re.compile() and then using methods such as  match() ,  findall() , or  finditer()

'''
# match dates specified as digits, such as “11/27/2012.”
test1 = '11/27/2012'
test2 = 'Nov 27, 2012'
import re
if re.match(r'\d+/\d+/\d+', test1):  # \d+ means match one or more digits
    print('yes')
else:
    print('no')

# If you’re going to perform a lot of matches using the same pattern, it usually pays to
# precompile the regular expression pattern into a pattern object first
datepat = re.compile(r'\d+/\d+/\d+')
if datepat.match(test1):
    print('yes')
else:
    print('no')

if datepat.match(test2):
    print('yes')
else:
    print('no')

# match(): find the first
# findall(): find all
test = 'Today is 11/27/2012. PyCon starts 3/13/2013.'
a = datepat.findall(test)
print(a)

datpat2 = re.compile(r'(\d+)/(\d+)/(\d+)')
m = datpat2.match('11/27/2012')
print(m)
b = m.group(0)
c = m.group(1)
d = m.group(2)
e = m.groups()
print(b)
print(c)
print(d)
print(e)
month, day, year = m.groups()
print(month)

print(test)
f = datpat2.findall(test)
print(f)
for month, day, year in datpat2.findall(test):
    print('{}-{}-{}'.format(year, month, day))

# The  findall() method searches the text and finds all matches, returning them as a list.
# If you want to find matches iteratively, use the  finditer() method instead
for m in datpat2.finditer(test):
    print(m.groups())

# If you want an exact match, make sure the pattern includes the end-marker ( $ )

n = datepat.match('11/27/2012abcdef')
datepat3 = re.compile(r'\d+/\d+/\d+$')
datepat4 = re.compile(r'(\d+)/(\d+)/(\d+)$')
i = datepat4.match('11/27/2012abcdef')
j = datepat4.match('11/27/2012')
print(i)
print(j)

# module-level functions
re.findall(r'(\d+)/(\d+)/(\d+)', test)
# (Be aware, though, that if you’re going to perform a lot of matching or searching, it usually
# pays to compile the pattern first and use it over and over again. The module-level func‐
# tions keep a cache of recently compiled patterns, so there isn’t a huge performance hit,
# but you’ll save a few lookups and extra processing by using your own compiled pattern.)
